﻿package com.skillscoach
{
	import alducente.services.WebService;
	import flash.display.MovieClip;
	import flash.media.Microphone;
	import org.bytearray.micrecorder.encoder.WaveEncoder;
	import org.bytearray.micrecorder.MicRecorder;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import org.bytearray.micrecorder.events.RecordingEvent;
	import flash.system.Security;
	import fl.transitions.Tween;
	import fl.transitions.easing.Strong;
	import flash.net.FileReference;
	import flash.display.LoaderInfo;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import org.as3wavsound.WavSound;
	import flash.utils.ByteArray;
	import flash.external.ExternalInterface;
	import flash.media.SoundChannel;
	import flash.utils.Timer;
	import com.skillscoach.RecordedClipObject;
	import flash.events.SampleDataEvent;
	import org.as3wavsound.WavSoundChannel;
	import flash.media.SoundTransform;
	



	public class TrimAudio extends MovieClip
	{
		
		public var stageClip:MovieClip = this as MovieClip;
		private var ws:WebService;
		private var mic:Microphone;
		private var waveEncoder:WaveEncoder = new WaveEncoder();
		private var recorder:MicRecorder = new MicRecorder(waveEncoder);
		private var recBar:RecBar = new RecBar();
		private var tween:Tween;
		private var fileReference:FileReference = new FileReference();
		private var paramObj:Object;
		private var recordedAudioFilePath:String = "http://media.onlineskillscoach.com/bic/audios";
		private var recordedAudioFileName:String;
		private var wavAudio:WavSound;
		private var wav:URLLoader;
		private var audioURLReq:URLRequest;
		private var recordedClipsArray:Array = new Array();
		private var savedAudioXMLLoader:URLLoader;
		private var audioIdToDelete:String;//-- Delete
		private var soundBytes:ByteArray = new ByteArray;
		private var myChannel:WavSoundChannel;
		private var seekbar:Seekbar;

		//time in milliseconds, set it to 1000 to display seconds
		private var time:int = 10;
		//create the timer object
		private var MyTimer:Timer = new Timer(time,0);
		private var currentPlayingClip:RecordedClip;
		private var isAudioPlaying:Boolean = false;
		private var curPos:Number = 0;
		private var trimBeginningValue:String = "";
		private var trimEndValue:String = "";
		
		

		public function TrimAudio()
		{
			//pauseBtn.addEventListener(MouseEvent.CLICK, loadRecordedAudio); //for testing
			Security.allowDomain("*");
		
			paramObj = LoaderInfo(this.root.loaderInfo).parameters;
			trace(typeof(paramObj.MessageId));
			//if(paramObj.
			//result_txt.text = "MemberId  : " + paramObj.MemberId + "ApplicationId  :  " + paramObj.ApplicationId + "  ManagerId  :  " + paramObj.ManagerId;
			// constructor code

			seekbar = new Seekbar();
			seekbar.x = 53;
			seekbar.y = 258;
			seekbar.trimBeg.visible = false;
			seekbar.trimEnd.visible = false;
			stageClip.addChild(seekbar);

			alphaLayer.enabled = false;
			stopBtn.enabled = false;
			stopBtn.alpha = .5;
			recBtn.stop();


			mic = Microphone.getMicrophone();
			mic.addEventListener(SampleDataEvent.SAMPLE_DATA, micSampleDataHandler);
			
			mic.gain = 100;
			//mic.rate = 44;
			//mic.setUseEchoSuppression(true);
			//mic.setLoopBack(true);
			
			
   
   // mic.setLoopBack(true);
    //mic.setUseEchoSuppression(true);
   // Security.showSettings("2");
			//mic.setLoopBack(true);
			//mic.setUseEchoSuppression(true);

			Security.showSettings("2");
			loadWSDL();
			addListeners();
		}


		private function micSampleDataHandler(event:SampleDataEvent):void { 
    		while(event.data.bytesAvailable)     { 
        		var sample:Number = event.data.readFloat(); 
        		soundBytes.writeFloat(sample); 
    		} 
		}

		private function addListeners():void
		{
			recBtn.addEventListener(MouseEvent.MOUSE_UP, startRecording);
			trimBtn.addEventListener(MouseEvent.CLICK, trimAudio);
			
			recorder.addEventListener(RecordingEvent.RECORDING, recording);
			recorder.addEventListener(Event.COMPLETE, recordComplete);
		}
		//closeBtn.addEventListener(MouseEvent.CLICK, closeApp);
	

	private function closeApp(evt:MouseEvent):void
	{
		ExternalInterface.call("CompleteRecording");
	}
	private function loadWSDL():void
	{
		ws = new WebService();
		ws.addEventListener(Event.CONNECT, wsdlConnected);
		//change here

		ws.connect("http://test2.nunationtech.com/Service/AudioRecording.asmx?wsdl");
		//ws.connect(paramObj.XMLServicePath + "?WSDL");
	}
	private function wsdlConnected(evt:Event):void
	{
		trace("web service  connected");
		alphaLayer.visible = false;

	}

	private function startRecording(e:MouseEvent):void
	{
		if (mic != null)
		{
			trace("came" + e.target.name);
			
			recorder.record();
			recBtn.gotoAndStop(2);
			recBtn.removeEventListener(MouseEvent.MOUSE_UP, startRecording);
			stopBtn.addEventListener(MouseEvent.MOUSE_UP, stopRecording);
			stopBtn.mouseChildren = false;
			stopBtn.alpha = 1;
			
			addChild(recBar);

			tween = new Tween(recBar,"y",Strong.easeOut, -  recBar.height,68,1,true);

			MyTimer.start();
		}
	}

	private function trimAudio(e:MouseEvent):void{
		//ws.TrimAudio(string from, string To, string AudioId,string MessageId)
		
		if(isAudioPlaying && trimBtn.currentFrame ==2)
		{
			trimBtn.gotoAndStop(3);
			trimBeginningValue = curPos.toString();
			seekbar.trimBeg.x = seekbar.seekbarBtn.x;
			seekbar.trimBeg.visible = true;
		}
		else if(isAudioPlaying && trimBtn.currentFrame == 3)
		{
			trimEndValue = curPos.toString();
			trimBtn.gotoAndStop(4);
			seekbar.trimEnd.x = seekbar.seekbarBtn.x;
			seekbar.trimEnd.visible = true;
		} 
		
		else if(trimBtn.currentFrame == 4)
		{
			ws.TrimAudio(audioTrimResponse, trimBeginningValue, trimEndValue, "3","1")
			trimBtn.gotoAndStop(1);
			seekbar.trimBeg.visible = false;
			seekbar.trimEnd.visible = false;
		} 
		
		
		
	}
	private function audioTrimResponse(serviceResponse:XML):void
	{
		
		trace(serviceResponse);
	}
	private function stopRecording(e:MouseEvent):void
	{
		recorder.stop();
		MyTimer.stop();
		//mic.setLoopBack(false);
		
		recBtn.gotoAndStop(1);
		recBtn.addEventListener(MouseEvent.MOUSE_UP, startRecording);
		stopBtn.removeEventListener(MouseEvent.MOUSE_UP, stopRecording);
		stopBtn.alpha = .5;

		tween = new Tween(recBar,"y",Strong.easeOut,0, -  recBar.height,1,true);
	}



	private function recording(e:RecordingEvent):void
	{

		recBar.counter.text = String(formatTime(MyTimer.currentCount));
		/*var currentTime:int = Math.floor(e.time / 1000);
		
		recBar.counter.text = String(currentTime);
		
		if (String(currentTime).length == 1)
		{
		recBar.counter.text = "00:00:0" + currentTime;
		}
		else if (String(currentTime).length == 2)
		{
		recBar.counter.text = "00:00:" + currentTime;
		}*/

	}

	

	private function formatTime( time:Number ):String
	{
		var remainder:Number;
		var hours:Number = time / (60 * 60);
		remainder = hours - (Math.floor ( hours ));
		hours = Math.floor(hours);
		var minutes = remainder * 60;
		remainder = minutes - (Math.floor ( minutes ));
		minutes = Math.floor(minutes);
		var seconds = remainder * 60;
		remainder = seconds - (Math.floor ( seconds ));
		seconds = Math.floor(seconds);
		var hString:String = hours < 10 ? "0" + hours:"" + hours;
		var mString:String = minutes < 10 ? "0" + minutes:"" + minutes;
		var sString:String = seconds < 10 ? "0" + seconds:"" + seconds;
		if (time < 0 || isNaN(time))
		{
			return "00:00:00";
		}
		if (hours > 0)
		{
			return "00:"+hString + ":" + mString;
		}
		else
		{
			return "00:00:" + mString;
		}
	}

	private function recordComplete(e:Event):void
	{
		stopBtn.alpha = 1;
		stageClip.stopBtn.addEventListener(MouseEvent.CLICK, saveAudio);
		stageClip.stopBtn.buttonMode = true;
		//fileReference.save(recorder.output, "recording.wav");
	}


	private function saveAudio(evt:MouseEvent):void
	{
		//enableBtn(recBtn, false);
		
		
		recBtn.removeEventListener(MouseEvent.MOUSE_UP, startRecording);
		stopBtn.removeEventListener(MouseEvent.MOUSE_UP, stopRecording);
		recBtn.alpha = .5;
		//result_txt.text = "Uploading your recorded audio...";
		try
		{
			recorder.stop();
			stageClip.recordBtn.gotoAndStop(1);
		}
		catch (e)
		{

		}


		if (recorder.output)
		{
			trace("null");
			//change here
			ws.SaveAudio(saveAudioResponse, '1', '2', 'athlete', Base64.encode(recorder.output));
			//ws.SaveAudio(string MessageId, string UserId, string UserType, byte[] SavedAudio)
			//ws.SaveAudio(saveFrameResponse, paramObj.ApplicationId , paramObj.MemberId, paramObj.ManagerId, Base64.encode(recorder.output)); // -old
		}
		else
		{
			
		}
	}

	private function saveAudioResponse(serviceResponse:XML):void
	{

		//delBtn.addEventListener(MouseEvent.CLICK, deleteRecordedAudio);
		recBtn.addEventListener(MouseEvent.MOUSE_UP, startRecording);
		stopBtn.removeEventListener(MouseEvent.MOUSE_UP, stopRecording);
		stageClip.stopBtn.alpha = .5;
		recBtn.alpha = 1;
		recBtn.gotoAndStop(1);
		
		var savedAudioXML:String = String(serviceResponse.children().children().children());
		
		trace(serviceResponse);
		trace(savedAudioXML + "  is the xml");
		// pleasewaitMc.visible = false;
		//recorder.output = null;
		
		
		//loadRecordedAudio();
		savedAudioXMLLoader = new URLLoader();
		savedAudioXMLLoader.addEventListener(Event.COMPLETE, onSavedAudioXMLLoadComplete);
		savedAudioXMLLoader.load(new URLRequest(savedAudioXML+"?random="+getCurrentTime()));


	}
	
	private function onSavedAudioXMLLoadComplete(evt:Event):void
	{
		var savedAudioXML:XML = new XML(evt.target.data);
		var recAudioClipObj:RecordedClipObject = new RecordedClipObject();
		recAudioClipObj.audioId = savedAudioXML.Audio.AudioId;
		recAudioClipObj.messageId = savedAudioXML.Audio.MessageId;
		recAudioClipObj.fileName = savedAudioXML.Audio.FileName;
		recAudioClipObj.audioPath = savedAudioXML.Audio.AudioPath;
		
		recordedClipsArray.push(recAudioClipObj);
		layoutRecordedClips();
		
		
	}
	
	private function layoutRecordedClips():void
	{
		
		
		for (var i:uint=0; i<recordedClipsArray.length; i++)
		{
			var recAudioClipObj:RecordedClipObject = recordedClipsArray[i];
			var recordedClip:RecordedClip  =  new RecordedClip();
			recordedClip.name = "recClip"+i;
			recordedClip.y = i* 42;
			recordedClip.audioId = recAudioClipObj.audioId;
			recordedClip.audioPath = recAudioClipObj.audioPath;
			recordedClip.recordedClipTitle.text = recAudioClipObj.fileName;
			recordedClipHolder.addChild(recordedClip);
			
			recordedClip.recordedClipDelBtn.addEventListener(MouseEvent.CLICK, deleteRecordedClip);
			recordedClip.recordedClipPlayBtn.addEventListener(MouseEvent.CLICK, loadRecordedAudio);
			recordedClip.recordedClipPlayBtn.useHandCursor = true;
			recordedClip.recordedClipPlayBtn.mouseEnabled = true;
			
		}
	}
	private function deleteRecordedClip(evt:MouseEvent):void
	{
		
		//ws.DeleteAudio(string audioFileId,string messageId)
		var clip:RecordedClip = new RecordedClip();
		audioIdToDelete = evt.currentTarget.parent.audioId;
		ws.DeleteAudio(delRecClipResponse,  audioIdToDelete,"1");
		
		trace(audioIdToDelete);
	}
	private function delRecClipResponse(serviceResponse:XML)
	{
		trace("here")
		wavAudio = null;
		
		for(var i:uint= 0 ;i<recordedClipsArray.length; i++)
		{
			trace("deleting" + audioIdToDelete)
			var recAudioClipObj:RecordedClipObject = recordedClipsArray[i];
			if(recAudioClipObj.audioId == audioIdToDelete ){
				recordedClipsArray.splice(i,1);
				trace("deleted")
			}
		}
		trace(recordedClipsArray.length);
		while (recordedClipHolder.numChildren > 0){ recordedClipHolder.removeChildAt(0); }
		layoutRecordedClips();
		
	}
	
	
	private function loadRecordedAudio(evt:MouseEvent):void
	{
		wav = new URLLoader();
		currentPlayingClip = evt.currentTarget.parent;
		audioURLReq = new URLRequest(currentPlayingClip.audioPath);//for testing
		//audioURLReq = new URLRequest("http://localhost/wavtest/68_20120709_1302_19_168.wav");
		//result_txt.text = "Loading audio please wait...";
		result_txt.text = "Loading Audio";
		
		wav.dataFormat = 'binary';
		wav.load(audioURLReq);
		wav.addEventListener(Event.COMPLETE, playRecordedAudio);
	}
	private function playRecordedAudio(evt:Event):void
	{
		trimBtn.gotoAndStop(1);
		seekbar.trimBeg.visible = false;
		seekbar.trimEnd.visible = false;
		
		wavAudio = new WavSound(evt.target.data as ByteArray);
		var st:SoundTransform = new SoundTransform();
		
		result_txt.text = "Playing";
		currentPlayingClip.recordedClipPlayBtn.gotoAndStop(2);
		
		
		myChannel = wavAudio.play();
		isAudioPlaying = true;
		trimBtn.gotoAndStop(2);
		stageClip.addEventListener(Event.ENTER_FRAME, findSeek);
	}
	
	private function findSeek(evt:Event):void
	{
		curPos =Number((myChannel.position/1000).toFixed(0));
		var totalLength:Number = Number((wavAudio.length/1000).toFixed(0));
		
		seekbar.progressHandler(curPos,totalLength);
		
		
		trace(curPos + " of " + totalLength);
		if((curPos+1) > totalLength){
			myChannel.stop();
			currentPlayingClip.recordedClipPlayBtn.gotoAndStop(1);//-- change play pause button
			//seekbar.resetSeek();
			isAudioPlaying = false;
			stageClip.removeEventListener(Event.ENTER_FRAME, findSeek);
			
			
			
		}
		
	}

	private function stopRecordedAudio(evt:MouseEvent):void
	{
		
	}
	private function enableBtn(btn:MovieClip, bool:Boolean):void
	{
		if (bool)
		{
			btn.alpha = 1;
			btn.enabled = bool;
		}
		else
		{
			btn.alpha = .5;
			btn.enabled = bool;
		}
	}
	private function getCurrentTime():String
	{
		var curTime = new Date();
		return String(curTime.getTime());
	}
}

}